<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="分类">
          <a-select
            v-decorator="[ 'productCategoryId', validatorRules.productCategoryId]"
            style="width: 100%"
            :getPopupContainer="node => node.parentNode"
            placeholder="请选择商品分类">
            <a-select-option v-for="(category,categoryIndex) in categoryList" :key="categoryIndex.toString()"
                             :value="category.id">
              {{ category.name }}
            </a-select-option>
          </a-select>
<!--          <j-dict-select-tag v-decorator="['productCategoryId', validatorRules.productCategoryId]" placeholder="请选择商品分类" :triggerChange="true" dictCode="pms_product_category,name,id,show_status='1' order by sort"/>-->
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="名称">
          <a-input placeholder="请输入名称" v-decorator="['name', validatorRules.name]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="图标">
          <a-upload
            listType="picture-card"
            class="logo-uploader"
            :showUploadList="false"
            :action="uploadAction"
            :data="{'isup':1,'dir':'product/tag'}"
            :headers="headers"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="picUrl" :src="getUrlView()" alt="url" style="height:104px;max-width:300px"/>
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import pick from 'lodash.pick'
import moment from 'moment'
import Vue from 'vue'

export default {
  name: 'PmsProductTagModal',
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },

      confirmLoading: false,
      uploadLoading:false,
      headers:{},
      picUrl: "",
      categoryList: [],
      form: this.$form.createForm(this),
      validatorRules: {
        productCategoryId: { rules: [{ required: true, message: '请选择分类!' }] },
        name: { rules: [{ required: true, message: '请输入名称!' }] }
      },
      url: {
        fileUpload: window._CONFIG['domianURL']+"/sys/common/ossUpload",
        imgerver: window._CONFIG['domianURL']+"/sys/common/view",
        add: '/pms/pmsProductTag/add',
        edit: '/pms/pmsProductTag/edit',
        getProductCategorys: '/pms/pmsProductCategory/getProductCategorys',
      }
    }
  },
  created () {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = {"X-Access-Token":token};
  },
  computed:{
    uploadAction:function () {
      return this.url.fileUpload;
    }
  },
  methods: {
    add() {
      this.picUrl = "";
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.getCategoryList()
      this.model = Object.assign({}, record)
      this.picUrl = this.model.url;
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'productCategoryId', 'name'))
        //时间格式化
      })

    },
    getCategoryList() {
      getAction(this.url.getProductCategorys, {}).then(res => {
        if (res.success) {
          this.categoryList = res.result
        } else {
          console.log(res.message)
        }
      })
    },
    beforeUpload: function(file){
      let fileType = file.type;
      if(fileType.indexOf('image')<0){
        this.$message.warning('请上传图片');
        return false;
      }
      //TODO 验证文件大小
    },
    handleChange (info) {
      this.picUrl = "";
      if (info.file.status === 'uploading') {
        this.uploadLoading = true;
        return
      }
      if (info.file.status === 'done') {
        var response = info.file.response;
        this.uploadLoading = false;
        console.log(response);
        if(response.success){
          this.model.url = response.message;
          this.picUrl = this.model.url;
        }else{
          this.$message.warning(response.message);
        }
      }
    },
    getUrlView(){
      if(this.model.url !== null && this.model.url !== undefined && this.model.url !== ''){
        if('http' === this.model.url.substring(0,4)){
          return this.model.url;
        }
        return this.url.imgerver +"/"+ this.model.url;
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          //时间格式化

          console.log(formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })


        }
      })
    },
    handleCancel() {
      this.close()
    }


  }
}
</script>

<style lang="less" scoped>

</style>